package com.jjwxc.jwjskandriod.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.ManageViewHolder;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.widget.MyDialog;
import com.jjwxc.jwjskandriod.model.BookCaseResponse;
import com.jjwxc.jwjskandriod.model.DelectRequest;
import com.jjwxc.jwjskandriod.model.UpdataGroupRequest;
import com.jjwxc.jwjskandriod.widget.GroupPop;

import java.util.ArrayList;
import java.util.List;

public class BookManageActivity extends BaseActivity {
    private RecyclerView rv_bookmanage;

    private TextView tv_select;
    private TextView tv_all;
    private BookManageAdapter adapter;

    private LinearLayout ll_move;
    private LinearLayout ll_similarity;
    private LinearLayout ll_delect;
    private String data;
    private int num = 0;
    private int page;
    private XRefreshView refreshView;
    public static long lastRefreshTime;
    List<BookCaseResponse.DataBean> mList = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_bookmanage;
    }

    @Override
    public void findView() {
        rv_bookmanage = findViewById(R.id.rv_bookmanage);
        tv_select = findViewById(R.id.tv_select);
        tv_all = findViewById(R.id.tv_all);
        ll_move = findViewById(R.id.ll_move);
        ll_similarity = findViewById(R.id.ll_similarity);
        ll_delect = findViewById(R.id.ll_delect);
        refreshView = findViewById(R.id.book_view);
    }

    @Override
    public void setListener() {
        setNoTitle();
        tv_all.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mList.size(); i++) {
                    mList.get(i).getBook().setSelect(true);
                }
                num = mList.size();
                tv_select.setText("收藏已选择" + mList.size() + "本");
                adapter.notifyDataSetChanged();
                ll_similarity.setVisibility(View.INVISIBLE);
            }
        });
        ll_similarity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String bookId = "";
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getBook().isSelect()) {
                        bookId = mList.get(i).getBookId();
                    }
                }
                Intent intent = new Intent(BookManageActivity.this, SimilarityActivity.class);
                intent.putExtra("bookId", bookId);
                startActivity(intent);
            }
        });
        ll_move.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (num <= 0) {
                    showToast("请先选择书籍");
                    return;
                }
                GroupPop.collentGroupPop(v, BookManageActivity.this, group -> {
                    if (group == null) {
                        return;
                    }
                    List<String> bookcaseIds = new ArrayList<>();
                    for (int i = 0; i < mList.size(); i++) {
                        if (mList.get(i).getBook().isSelect()) {
                            bookcaseIds.add(mList.get(i).getBookcaseId());
                        }
                    }
                    UpdataGroupRequest request = new UpdataGroupRequest();
                    request.setBookcaseGroupId(group);
                    request.setBookcaseIds(bookcaseIds);
                    post(Url.updateBookcase, null, String.class, new FFNetWorkCallBack<String>() {
                        @Override
                        public void onSuccess(String response) {
                            if (response.contains("200")) {
                                getListUserBookcase(data, 0);
                                FFApplication.showToast("移动完成");
                                num = 0;
                                tv_select.setText("收藏已选择0本");
                            }
                        }

                        @Override
                        public boolean onFail(String response) {
                            return false;
                        }
                    }, JSON.toJSONString(request));

                });
            }
        });
        ll_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> bookcaseIds = new ArrayList<>();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getBook().isSelect()) {
                        bookcaseIds.add(mList.get(i).getBookcaseId());
                    }
                }
                if (bookcaseIds.size() <= 0) {
                    showToast("请先选中后删除");
                    return;
                }
                new MyDialog(BookManageActivity.this, "你确定删除收藏的书籍吗", "确定", "取消", new MyDialog.DialogClickListener() {
                    @Override
                    public void onOkClick(Dialog dialog) {

                        DelectRequest request = new DelectRequest();
                        request.setBookcaseIds(bookcaseIds);
                        post(Url.removeBookcase, "", String.class, new FFNetWorkCallBack<String>() {
                            @Override
                            public void onSuccess(String response) {
                                getListUserBookcase(data, 0);
                            }

                            @Override
                            public boolean onFail(String response) {
                                return false;
                            }
                        }, JSON.toJSONString(request));
                    }

                    @Override
                    public void onNoClick(Dialog dialog) {

                    }
                }).show();

            }
        });

        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                num = 0;
                getListUserBookcase(data, page);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                getListUserBookcase(data, page * 20);
            }
        });
    }

    @Override
    public void afterCreate() {
        data = getIntent().getStringExtra("book_tab");
        tv_select.setText("收藏已选择0本");
        rv_bookmanage.setNestedScrollingEnabled(false);
        rv_bookmanage.setFocusable(false);
        rv_bookmanage.setLayoutManager(new GridLayoutManager(this, 4));
        rv_bookmanage.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new BookManageAdapter(this);
        rv_bookmanage.setAdapter(adapter);

        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(BookManageActivity.this));
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);
        getListUserBookcase(data, 0);
    }

    public void getListUserBookcase(String groupId, int page) {
        ll_similarity.setVisibility(View.INVISIBLE);
        if (page == 0) {
            refreshView.setLoadComplete(false);
        }
        String msg;
        if (groupId == null) {
            msg = "{\"offset\":" + page + ",\"limit\":20}";
        } else {
            msg = "{\"offset\":" + page + ",\"limit\":20,\"bookcaseGroupId\":\"" + groupId + "\"}";
        }
        post(Url.listUserBookcase, null, BookCaseResponse.class,
                new FFNetWorkCallBack<BookCaseResponse>() {
                    @Override
                    public void onSuccess(BookCaseResponse response) {
                        lastRefreshTime = refreshView.getLastRefreshTime();
                        if (response.getCode() == 200) {
                            tv_select.setText("收藏已选择" + num + "本");
                            if (page == 0) {
                                mList.clear();
                            }
                            mList.addAll(response.getData());
                            if (response.getData() == null || response.getData().size() < 20) {
                                refreshView.setLoadComplete(true);
                            }
                            if (page == 0) {
                                refreshView.stopRefresh();
                                adapter.setData(response.getData());
                            } else {
                                refreshView.stopLoadMore();
                                adapter.addData(response.getData());
                            }
                        }

                    }

                    @Override
                    public boolean onFail(BookCaseResponse response) {
                        return false;
                    }
                }, msg);
    }

    public class BookManageAdapter extends BaseRecyclerAdapter<ManageViewHolder> {
        private Context context;


        private List<BookCaseResponse.DataBean> mData = new ArrayList<>();


        public BookManageAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<BookCaseResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<BookCaseResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public ManageViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.manage_book_item, parent, false);
            ManageViewHolder viewHolder_text = new ManageViewHolder(mView);
            return viewHolder_text;

        }

        @Override
        public ManageViewHolder getViewHolder(View view) {
            return new ManageViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @Override
        public void onBindViewHolder(final ManageViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            holder.txt_manage_book.setText(mData.get(position).getBook().getName());
            FFImageLoader.loadImage(context, holder.img_manage_book, mData.get(position).getBook().getCoverImgUrl() + "", mData.get(position).getBookId(), true);
            if (mData.get(position).getBook().isSelect()) {
                holder.img_manage_book.setBackgroundResource(R.drawable.select_item);
                holder.img_xuan.setVisibility(View.VISIBLE);
            } else {
                holder.img_manage_book.setBackgroundResource(R.color.white);
                holder.img_xuan.setVisibility(View.GONE);
            }
            holder.ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.get(position).getBook().isSelect()) {
                        num--;
                        mData.get(position).getBook().setSelect(false);
                    } else {
                        num++;
                        mData.get(position).getBook().setSelect(true);
                    }
                    if (num == 1) {
                        ll_similarity.setVisibility(View.VISIBLE);
                    } else {
                        ll_similarity.setVisibility(View.INVISIBLE);
                    }
                    tv_select.setText("收藏已选择" + num + "本");
                    notifyItemChanged(position);
                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }

}


